package leetcode.easy.q07;

/**
 * @see {https://leetcode-cn.com/problems/reverse-integer/}
 */
public class Question7 {
    public static void main(String[] args) {
        System.out.println(new Solution().reverse(1534236469));
        System.out.println(new Solution2().reverse(1534236469));
        System.out.println(new Solution3().reverse(1534236469));
        System.out.println(new Solution4().reverse(1534236469));
    }
}

/**
 * 基于字符串算
 */
class Solution {
    public int reverse(int x) {
        String numStr = String.valueOf(x);
        long result = 0;
        int startIndex = 0;
        if (numStr.startsWith("-")) {
            startIndex = 1;
        }
        int flag = startIndex == 0 ? 1 : -1;

        for (int i = numStr.length() - 1; i >= startIndex; i--) {
            long y = ((int) numStr.charAt(i) - (int) '0') * pow10(i - startIndex);
            result = result + y;
            if (result > Integer.MAX_VALUE || result < 0) {
                return 0;
            }
        }
        return (int) result == result ? (int) result*flag : 0;
    }

    private long pow10(int i) {
        if (i == 0) {
            return 1L;
        }
        return 10L * (pow10(i - 1));
    }
}

class Solution2 {
    public int reverse(int x) {
        String numStr = String.valueOf(x);
        int result = 0;
        int startIndex = 0;
        if (numStr.charAt(0) == '-') {
            startIndex = 1;
        }
        int flag = startIndex == 0 ? 1 : -1;

        for (int i = numStr.length() - 1; i >= startIndex; i--) {
            double y = ((int) numStr.charAt(i) - (int) '0') * Math.pow(10, i - startIndex);
            result = result + Double.valueOf(y).intValue();
            if (result > Integer.MAX_VALUE || result < 0) {
                return 0;
            }
        }
        return result * flag;
    }
}

class Solution3 {
    public int reverse(int x) {
        long result = 0L;
        while (x != 0) {
            result += result * 10 + x % 10;//个位
            x = x / 10;//舍去个位
        }
        return (int) result == result ? (int) result : 0;
    }
}

class Solution4 {
    public int reverse(int x) {
        String numStr = String.valueOf(x);
        StringBuilder sb = null;
        Integer flag = 1;
        if ('-' == numStr.charAt(0)) {
            sb = new StringBuilder(numStr.substring(1));
            flag = -1;
        } else {
            sb = new StringBuilder(numStr);
        }
        StringBuilder resSb = sb.reverse();
        try {
            return Integer.valueOf(resSb.toString()) * flag;
        }catch (Exception e){
            return 0;
        }
    }
}